/**
 * Ant Design Pro v4 use `@ant-design/pro-layout` to handle Layout.
 * You can view component api by:
 * https://github.com/ant-design/ant-design-pro-layout
 */
import ProLayout, {
  MenuDataItem,
  BasicLayoutProps as ProLayoutProps,
  Settings,
} from '@ant-design/pro-layout';
import React, { useEffect, useMemo, useRef,useState } from 'react';
import { Link, useIntl, connect, Dispatch, history, TabsLayout } from 'umi';
import { Result, Button } from 'antd';
import Authorized from '@/utils/Authorized';
import RightContent from '@/components/GlobalHeader/RightContent';
import { ConnectState } from '@/models/connect';
import { LoginUserItemType, StateType } from '@/models/login';
import { getMatchMenu } from '@umijs/route-utils';
import logo from '../assets/logo.png';
import {  Modal, Avatar, Radio } from 'antd';
import styles from '@/pages/user/login/index.less';
import avatar from '@/assets/avatar.png';

const noMatch = (
  <Result
    status={403}
    title="403"
    subTitle="Sorry, you are not authorized to access this page."
    extra={
      <Button type="primary">
        <Link to="/user/login">跳转登录</Link>
      </Button>
    }
  />
);
export interface BasicLayoutProps extends ProLayoutProps {
  breadcrumbNameMap: {
    [path: string]: MenuDataItem;
  };
  route: ProLayoutProps['route'] & {
    authority: string[];
  };
  settings: Settings;
  dispatch: Dispatch;
  userLogin: StateType;
}
export type BasicLayoutContext = { [K in 'location']: BasicLayoutProps[K] } & {
  breadcrumbNameMap: {
    [path: string]: MenuDataItem;
  };
};
/**
 * use Authorized check all menu item
 */

const menuDataRender = (menuList: MenuDataItem[]): MenuDataItem[] =>
  menuList.map((item) => {
    const localItem = {
      ...item,
      children: item.children ? menuDataRender(item.children) : undefined,
    };
    return Authorized.check(item.authority, localItem, null) as MenuDataItem;
  });

const BasicLayout: React.FC<BasicLayoutProps> = (props) => {
  const {
    dispatch,
    settings,
    userLogin = {},
    location = {
      pathname: '/',
    },
  } = props;

  const { users } = userLogin;
  const [visible, setVisible] = useState<boolean>(false); // 是否显示登录账号的弹窗。
  const [chooseUser, setChooseUser] = useState<LoginUserItemType | undefined>(undefined); // 设置选择的登录账号
  const menu = [
    {
      path: '/order/cabinet',
      title: '充电宝订单',
    },
    {
      path: '/order/powerline',
      title: '充电线订单',
    },
    {
      path: '/welcome',
      title: '欢迎'
    },
    {
      path: '/device/cabinet',
      title: '机柜管理'
    },
    {
      path: '/device/powerline',
      title: '充电线管理'
    },
    {
      path: '/statistic/seller',
      title: '商户统计'
    },
    {
      path: '/seller',
      title: '商户管理'
    }
  ];

  const menuDataRef = useRef<MenuDataItem[]>([]);
  // 判断是否登录
  useEffect(() => {
    // console.log('【登录状态】', userLogin);
    if (users && users.length > 0) {
      setChooseUser(users[0]);
      setVisible(true);
    }
  }, [userLogin]);

  useEffect(() => {
    if (dispatch) {
      dispatch({
        type: 'user/fetchCurrent',
      });
    }
  }, []);

  // 取消登录
  const cancelLogin = () => {
    setVisible(false);
  }
  // 确定登录用户
  const confrimLogin = () => {
    setVisible(false);

    dispatch({
      type: 'login/chooseUser',
      payload: { 
        id: chooseUser?.uid,
        user_type: chooseUser?.type,
        token: chooseUser?.token,
       }
    })
    dispatch({
        type: 'user/fetchCurrent',
    });
    window.location.reload(true);
  }
  /**
   * init variables
   */

  const handleMenuCollapse = (payload: boolean): void => {
    if (dispatch) {
      dispatch({
        type: 'global/changeLayoutCollapsed',
        payload,
      });
    }
  };
  // get children authority
  const authorized = useMemo(
    () =>
      getMatchMenu(location.pathname || '/', menuDataRef.current).pop() || {
        authority: undefined,
      },
    [location.pathname],
  );

  const { formatMessage } = useIntl();
  console.log(props);
  return (
    <ProLayout
      logo={logo}
      formatMessage={formatMessage}
      {...props}
      {...settings}
      title="优电商户"
      onCollapse={handleMenuCollapse}
      onMenuHeaderClick={() => history.push('/')}
      menuItemRender={(menuItemProps, defaultDom) => {
        if (menuItemProps.isUrl || !menuItemProps.path) {
          return defaultDom;
        }
        return <Link to={menuItemProps.path}>{defaultDom}</Link>;
      }}
      breadcrumbRender={(routers = []) => [
        {
          path: '/',
          breadcrumbName: formatMessage({ id: 'menu.home' }),
        },
        ...routers,
      ]}
      itemRender={(route, params, routes, paths) => {
        const first = routes.indexOf(route) === 0;
        return first ? (
          <Link to={paths.join('/')}>{route.breadcrumbName}</Link>
        ) : (
          <span>{route.breadcrumbName}</span>
        );
      }}
      menuDataRender={menuDataRender}
      rightContentRender={() => <RightContent />}
      postMenuData={(menuData) => {
        menuDataRef.current = menuData || [];
        return menuData || [];
      }}
    >
      <Authorized authority={authorized!.authority} noMatch={noMatch}>
            <TabsLayout {...props} menu={menu}/>
      </Authorized>
      {/* 选择登录账号弹窗 */}
          <Modal
            title="选择登录账号"
            centered
            visible={visible}
            onOk={() => confrimLogin()}
            onCancel={() => cancelLogin()}
            width={1000}
          >
            <div className={styles.userList}>
              {users?.map((item, index) => { return <div
                onClick={() => setChooseUser(item)}
                className={styles.userItem} key={index}>
                  {/* 头像 */}
                  <Avatar src={avatar} size="large"/>
                  {/* 信息 */}
                  <div className={styles.userInfo}>
                    <div className={styles.userTitle}>{item.uid + "-" + item.name}</div>
                    <div className={styles.userTip}>{item.oid}</div>
                  </div>
                  <Radio checked={chooseUser && chooseUser.uid === item.uid}></Radio>
                </div>
              })}
            </div>
          </Modal>
    </ProLayout>
  );
};

export default connect(({ global, settings,login }: ConnectState) => ({
  collapsed: global.collapsed,
  settings,
  userLogin: login,
}))(BasicLayout);
